package com.zmwx.wx.handler;
import com.zmwx.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler{
    private static final String KEY_WORD = "验证码";
    @Resource
    private RedisUtil redisUtil;
    private static final String LOGIN_PREFIX = "loginCode";

    @Override
    public WxChatMassageTypeEnum getMsgType() {
        return WxChatMassageTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String,String> messageMap) {
        log.info("处理文本消息");
        String content = messageMap.get("Content");
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        if (KEY_WORD.equals(content)) {
            //生成验证码
            Random random=new Random();
            int num = random.nextInt(1000);
            String numKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(num));
            redisUtil.setNx(numKey, fromUserName, 5L, TimeUnit.MINUTES);
            String numContent = "您当前的验证码是：" + num + "！ 5分钟内有效";
          return   getReturnXml(fromUserName, toUserName, numContent);
        } else if (content.equals("天王盖地虎")) {
            return   getReturnXml(fromUserName, toUserName, "宝塔镇河妖！");
        }else {
            return   getReturnXml(fromUserName, toUserName, "小阿怡乖乖");
        }

    }
    public String getReturnXml(String fromUserName, String toUserName,String content){
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + content + "]]></Content>\n" +
                "</xml>";

        return replyContent;
    }
}
